import { Tools } from "../../common/Tools";
import { AudioManager1 } from "../../manager/AudioManager1";
import { EventManager } from "../../manager/EventManager";
import { UIManager } from "../../manager/UIManager";
import TouchScale from "../../item/Common/TouchScale";
import LevelBase from "../../LevelBase";
import LvItem from "../../LvItem";
import LvItem_14 from "./LvItem_14";
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../../base/EnumIndex";
import { TOUCH_MOVE_LEN } from "../../base/GameIndex";

const { ccclass, property } = cc._decorator;

/** 找茬类关卡 */
@ccclass
export default class LevelPre_14 extends LevelBase {
    @property(cc.Node)
    tipLabNode: cc.Node = null;
    @property(cc.Node)  //提示文字
    tipNode: cc.Node = null;

    @property(cc.Node)
    maskNode: cc.Node = null;
    @property(cc.Node)
    viewBg: cc.Node = null;
    @property(cc.Node)
    downContent: cc.Node = null;
    @property(cc.Node)
    downItem: cc.Node = null;


    @property(cc.Node)
    btnLeft: cc.Node = null;
    @property(cc.Node)
    btnRight: cc.Node = null;
    /**当前页数 */
    currPage: number = 1;
    /**最大页数 */
    maxPage: number = 12;
    /**已完成页数 */
    finishPages: number[] = [];

    @property(cc.Label)   //故事背景
    storyLab: cc.Label = null;
    @property(cc.Node)   //故事背景节点
    storyNode: cc.Node = null;

    scoreNum: number = 0;
    /** 已经完成的游戏状态 */
    finishStateArr: Array<string> = [];
    /** 本关的交互配置 */
    interJson: any = null;

    start() {
        EventManager.ins.on(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finishTween, this);
        cc.macro.ENABLE_MULTI_TOUCH = true;  //是否开起多点触摸
    }
    onDestroy(): void {
        super.onDestroy();
        EventManager.ins.off(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finishTween, this);
        this.unscheduleAllCallbacks();
    }


    /**初始化翻页按钮 */
    initPage() {
        this.currPage = 1;
        this.fixBtn();
        this.maskNode.getChildByName("huaPre").getChildByName("bg_" + this.currPage).active = true;
        this.btnLeft.on("click", () => {
            this.currPage--;
            this.maskNode.getChildByName("huaPre").getChildByName("bg_" + (this.currPage + 1)).active = false;
            this.maskNode.getChildByName("huaPre").getChildByName("bg_" + this.currPage).active = true;
            this.fixBtn();
        });
        this.btnRight.on("click", () => {
            this.currPage++;
            this.maskNode.getChildByName("huaPre").getChildByName("bg_" + (this.currPage - 1)).active = false;
            this.maskNode.getChildByName("huaPre").getChildByName("bg_" + this.currPage).active = true;
            this.fixBtn();
        })
    }

    fixBtn() {
        if (this.currPage <= 1) {
            this.btnLeft.active = false;
        }
        else if (this.currPage >= 12) {
            this.btnRight.active = false;
        }
        else {
            this.btnLeft.active = this.btnRight.active = true;
        }
    }
    /** 初始化所有的item */
    init(huaPre: cc.Prefab) {
        this.loadJson();
        if (this.interJson.isShowLab) {
            this.downItem.getChildByName("itemLab").active = true;
        }

        for (let i = 0; i < this.interJson.downItems.length; i++) {
            let node = cc.instantiate(this.downItem);
            node.y = 0;
            let config = this.interJson.downItems[i];
            if (!config.id) { config.id = (i + 1); }
            // cc.log(config.id, "LvItem_14")
            node.addComponent(LvItem_14).initItem(config, this);
            node.addComponent(LvItem).initItem(this);
            node.name = "popItem_" + config.id;
            node.getChildByName("itemLab").zIndex = 100;
            this.downContent.addChild(node);
        }

        this.huaNode = cc.instantiate(huaPre);
        this.maskNode.addChild(this.huaNode);
        // 适配
        let widthScale = this.maskNode.width / this.huaNode.width;
        let heightScale = this.maskNode.height / this.huaNode.height;
        this.huaNode.scale = Math.min(widthScale, heightScale);
        this.huaNode.getComponent(TouchScale).maskNode = this.maskNode;

        this.initHuaItem();
        this.initTouch();

        if (this.interJson.isPage) {
            this.initPage();
        }

    };

    /** 加载本关Json */
    loadJson() {
        if (this.interJson.isPage) {
            this.btnLeft.active = this.btnRight.active = true;
        } else {
            this.btnLeft.active = this.btnRight.active = false;
        }

        if (this.interJson.storyTitle) {
            this.storyNode.active = true
        }

        if (this.interJson.hideItemBg) {  //隐藏道具栏背景,放大道具 hideItemBg
            this.downItem.getChildByName("Bg").active = false;
            this.downItem.getChildByName("itemSpr").scale = 1.5;
        }
        if (this.interJson.ScaleItem) {              //改变缩小放大道具栏道具大小
            if (this.interJson.ScaleItem > 0) {
                this.downItem.getChildByName("itemSpr").scale = this.interJson.ScaleItem;
                this.downItem.getChildByName("itemBg").scale = this.interJson.ScaleItem;
            }
        }

        if (this.interJson.randomOrder) {
            console.log(this.interJson.randomOrder,'suiji');
            
            Tools.aginSortArr(this.interJson.downItems);
        }
    };

    huaNode: cc.Node = null;   //画的节点
    finishTween(finishStr: any, lvItem: LvItem) {

        if (typeof finishStr != "string") {  //完成条件不是字符串
            if (finishStr.str) {  //提示说话
                this.showTipInfo(finishStr);
            }
            if (finishStr.sayInfo) {   //人物说话
                let isShow = false;
                if (finishStr.isShow) {
                    isShow = true;
                }
                this.sayNodeQipaoTween(finishStr.sayInfo, isShow);
            }
            return;
        }

        if (finishStr.includes("addState_")) {
            let str = finishStr.split("addState_")[1];
            this.addHaveStates([str]);
        }
        if (finishStr.includes("removeState_")) {
            let str = finishStr.split("removeState_")[1];
            this.removeStates([str]);
        }
        if (finishStr.includes("upSlider_")) {  //加进度条
            let str = finishStr.split("upSlider_")[1];
            this.updateSlider(parseInt(str));
        }

        if (finishStr.includes("addPop_")) {  //激活 一个新道具
            let str = finishStr.split("addPop_")[1];
            this.addPopNode(lvItem, parseInt(str));
        }
        if (finishStr.includes("hidePop_")) {  //隐藏 一个新道具
            let str = finishStr.split("hidePop_")[1];
            this.hidePopNode(parseInt(str));
        }
        if (finishStr.includes("returnPop_")) {  //返回原点
            let popID = finishStr.split("returnPop_")[1];
            let popNode = this.getDownItemForID(parseInt(popID));
            popNode.getComponent(LvItem_14).returnInitPos();
        }
        if (finishStr.includes("setClick_")) {  //设置一个lvItem_14的click
            let str = finishStr.split("setClick_")[1];
            this.setLvItemClick(lvItem.node, str == "true" ? true : false);
        }
        if (finishStr == "updateWin") {  //刷新是否胜利
            this.updateWin();
        }
        if (finishStr == "updateIsWin") {  //直接结算游戏
            this.updateIsWin();
        }
        if (finishStr.includes("tip_")) {  //刷新是否胜利
            let str = finishStr.split("tip_")[1];
            this.showTipLab(str);
        }
        if (finishStr.includes("overTime")) {
            let levelBase = cc.director.getScene().getChildByName("Canvas").getComponentInChildren(LevelBase);
            for (let i = 0; i < this.interJson.talkInfos.length; i++) {
                let states = this.interJson.talkInfos[i].state;
                let haveSates = this.interJson.talkInfos[i].haveSates;
                let isHave = false;
                if (states && !isHave) {
                    for (let j = 0; j < states.length; j++) {
                        if (this.finishStateArr.indexOf(states[j]) >= 0) {
                            isHave = true;
                            break;
                        }
                    }
                }
                if (haveSates && !isHave) {
                    for (let j = 0; j < haveSates.length; j++) {
                        if (this.finishStateArr.indexOf(haveSates[j]) < 0) {
                            isHave = true;
                            break;
                        }
                    }
                }
                if (!isHave) {
                    levelBase.runNodeTween(levelBase.node, levelBase.getInterTwForName(this.interJson.talkInfos[i].tweenName).interTween)
                    return;
                }
            }
            UIManager.ins.enabledClick(false);
            return levelBase.runNodeTween(levelBase.node, levelBase.getInterTwForName("winGame").interTween)
        }
        if (finishStr.includes("showAchieve")) {
            let str = finishStr.split("showAchieve_")[1];
            let popID = parseInt(str);
            let popNode = this.getDownItemForID(popID);
            popNode.getChildByName("wancheng").active = true;
        }
        if (finishStr.includes("finishPage")) {
            let str = finishStr.split("finishPage_")[1];
            let page = Number(str);
            if (this.finishPages.indexOf(page) == -1) {
                this.finishPages.push(page);
            }
        }
        if (finishStr.includes("nextPage")) {
            for (let i = 1; i < 13; i++) {
                if (this.finishPages.indexOf(i) == -1) {
                    this.maskNode.getChildByName("huaPre").getChildByName("bg_" + (this.currPage)).active = false;
                    this.currPage = i;
                    this.maskNode.getChildByName("huaPre").getChildByName("bg_" + this.currPage).active = true;
                    this.fixBtn();
                    return;
                }
            }
        }
        if (finishStr.includes("storyTitle")) {
            let idx = finishStr.split("storyTitle_")[1];
            this.storyLab.string = this.interJson.storyTitle[idx];
        }
        if (finishStr.includes("costStep")) {
            EventManager.ins.emit(EVENT_NAME_ENUM.ADD_STEP, -1, () => {
                UIManager.ins.enabledClick(false);
                this.runNodeTween(this.viewBg, this.getInterTwForName("overGameAni").interTween);
            });
        }
        if (finishStr.includes("TcStep")) {   // 广告弹窗  判断是否步数为0,打开广告弹窗
            EventManager.ins.emit(EVENT_NAME_ENUM.ADD_STEP, -1);
        }

        if (finishStr.includes("stopTime")) {
            EventManager.ins.emit(EVENT_NAME_ENUM.STOP_TIME);
        }
        if (finishStr.includes("pauseTime")) {
            EventManager.ins.emit(EVENT_NAME_ENUM.PAUSE_TIME);
        }

    }

    /** 是否做过失败项 */
    getLose() {
        if (!this.interJson.loseStates || this.interJson.loseStates.length <= 0 || this.finishStateArr.length <= 0) { return false; }

        for (let i = 0; i < this.finishStateArr.length; i++) {
            if (this.interJson.loseStates.indexOf(this.finishStateArr[i]) >= 0) {
                return true;
            }
        }
        return false;
    };
    /** 是否做过插入项 */
    getCharu() {
        if (!this.interJson.charuStates || this.interJson.charuStates.length <= 0 || this.finishStateArr.length <= 0) { return false; }

        for (let i = 0; i < this.finishStateArr.length; i++) {
            if (this.interJson.charuStates.indexOf(this.finishStateArr[i]) >= 0) {
                return true;
            }
        }
        return false;
    };

    isTouchMove: boolean = false;  //是否按住移动
    touchStartPos: cc.Vec3 = null;
    /** 初始化触摸 */
    initTouch() {
        if (cc.sys.os == cc.sys.OS_WINDOWS) {
            this.huaNode.on(cc.Node.EventType.MOUSE_WHEEL, (touches: cc.Event.EventMouse) => {
                this.huaNode.getComponent(TouchScale).mouseWheelCall(touches);
            }, this);
        }
        this.huaNode.on(cc.Node.EventType.TOUCH_START, (touches: cc.Touch) => {
            this.isTouchMove = false;
            this.touchStartPos = cc.v3(touches.getLocation());
        }, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_MOVE, (touchs: cc.Event.EventTouch) => {
            if (!this.touchStartPos || Tools.getDistance(this.touchStartPos, touchs.getLocation()) <= TOUCH_MOVE_LEN) { return; }
            this.isTouchMove = true;
            this.huaNode.getComponent(TouchScale).touchMoveCall(touchs);
        }, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_END, this.huaTouchEnd, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_CANCEL, this.huaTouchEnd, this);
    };
    /** 图片节点触摸结束 */
    huaTouchEnd(touchs: cc.Event.EventTouch) {
        this.huaNode.getComponent(TouchScale).touchMoveEnd(touchs);
        this.isTouchMove = false;
    };
    /** 根据配置初始化 item */
    initHuaItem() {
        for (let i = 0; i < this.interJson.sceneItems.length; i++) {
            let config = this.interJson.sceneItems[i];
            let node = this.getChildForName(config.info);
            if (!node) { continue; }
            node.getComponent(LvItem_14).initItem(config, this);
        }
        if (this.interJson.initStates) {
            this.addHaveStates(this.interJson.initStates);
        }

        this.scheduleOnce(() => {
            for (let i = 0; i < this.interJson.hideItems.length; i++) {
                let id = this.interJson.hideItems[i];
                let node = this.getDownItemForID(id);
                if (node) {
                    node.active = false;
                }
            }
        }, 0);
    };

    lastAudio: string = null;
    /** 执行提示文字事件 */
    async showTipInfo(sayInfo: any) {
        let tempT = 0;
        if (sayInfo.audio) {
            // AudioManager.stopAllAudioDir(sayInfo.exclue);
            if (this.lastAudio) {
                AudioManager1.stopAudioForName(this.lastAudio);
            }
            let audio = await AudioManager1.playAudio(sayInfo.audio.resUrl, sayInfo.audio.value, BUNDLE_TYPE_ENUM.LEVEL);
            tempT = cc.audioEngine.getDuration(audio) + 0.2;
            this.lastAudio = sayInfo.audio.resUrl;
        } else if (sayInfo.time) {
            tempT = sayInfo.time;
        }
        if (sayInfo.str) {
            this.showTipNodeLab(sayInfo.str, tempT, sayInfo);
        }
        if (sayInfo.armAni) {
            this.runArmAni(sayInfo.armAni, sayInfo.armAni.shuo, sayInfo.armAni.node);
        }
        return tempT;
    };

    lastSayAudio: string = null;
    /** 执行气泡说话 */
    async sayNodeQipaoTween(sayInfo: any, isShow: boolean = false) {
        let sayNode = this.getChildForName(sayInfo.node);
        if (sayInfo.str && AudioManager1.isSubtitle) {
            sayNode.active = true;
            sayNode.getComponent(LvItem).setLabString(sayInfo.str);
        }

        if (sayInfo.armAni) {
            this.runArmAni(sayInfo.armAni, sayInfo.armAni.shuo, sayNode);
        }
        if (sayInfo.armAni2) {
            this.runArmAni(sayInfo.armAni2, sayInfo.armAni2.shuo, sayNode);
        }

        if (sayInfo.audio) {
            AudioManager1.stopAudioForName(this.lastSayAudio);
            let audio = await AudioManager1.playAudio(sayInfo.audio.resUrl, sayInfo.audio.value, BUNDLE_TYPE_ENUM.LEVEL);
            this.lastSayAudio = sayInfo.audio.resUrl;

            cc.Tween.stopAllByTarget(sayNode);
            let tempT = cc.audioEngine.getDuration(audio);
            cc.tween(sayNode)
                .delay(tempT)
                .call(() => {
                    if (!isShow) {
                        sayNode.active = false;
                    }
                    if (sayInfo.armAni) {
                        this.runArmAni(sayInfo.armAni, sayInfo.armAni.daiji, sayNode);
                    }
                    if (sayInfo.armAni2) {
                        this.runArmAni(sayInfo.armAni2, sayInfo.armAni.daiji, sayNode);
                    }
                }).start();
            return tempT;
        }
    };
    isHaveNoStates(state?: string | string[]) {
        cc.log("isHaveNoStates", state)
        if (!state) { return true; }
        if (typeof state === "string") {
            return this.finishStateArr.indexOf(state) < 0;
        } else {
            let count = 0;
            for (let i = 0; i < state.length; i++) {
                if (this.finishStateArr.indexOf(state[i]) < 0) {
                    count++;
                }
            }
            return count == state.length;
        }
    }
    /** 显示提示文字  time 显示时间 */
    showTipNodeLab(str: string, time: number, sayInfo: any) {
        cc.Tween.stopAllByTarget(this.tipNode);
        this.tipNode.active = AudioManager1.isSubtitle;
        let lab = this.tipNode.getComponentInChildren(cc.Label);
        if (str != "") {
            lab.string = str;
        }
        cc.tween(this.tipNode)
            .to(0.3, { opacity: 255 })
            .delay(time)
            .call(() => {
                if (sayInfo.armAni) {
                    this.runArmAni(sayInfo.armAni, sayInfo.armAni.daiji, sayInfo.armAni.node);
                }
                // if( this.interJson.autoSayIsWin ){
                //     this.updateIsWin();
                // }
            })
            .to(0.3, { opacity: 0 }).start();
    };
    /** 通过sayInfo执行龙骨动画 */
    runArmAni(armAni: any, aniName: string, sayNode?: cc.Node) {
        if (!armAni) { return; }
        let node = sayNode.parent;
        if (armAni.node) {
            node = this.getNodeForName(armAni.node);
        }
        node.getComponent(LvItem).playArmtureAni(aniName);
    };

    /** 刷新进度条进度 */
    updateSlider(value: number) {
        this.scoreNum += value;
        EventManager.ins.emit(EVENT_NAME_ENUM.UPDATE_SLIDER, this.scoreNum / 100)
    };
    /** 设置本关Item的Click */
    setLvItemClick(node: cc.Node, isClick: boolean) {
        if (node.getComponent(LvItem)) {
            node.getComponent(LvItem).isClick = isClick;
        }
        if (node.getComponent(LvItem_14)) {
            node.getComponent(LvItem_14).isClick = isClick;
        } else {
            cc.log("节点" + node.name + "上没有添加LvItem脚本");
        }
    };
    /** 激活一个新道具 */
    addPopNode(lvItem: LvItem, popID: number) {
        let popNode = this.getDownItemForID(popID);
        popNode.active = true;
        popNode.opacity = 0;

        this.scheduleOnce(() => {
            Tools.setNodeParent(lvItem.node, this.viewBg);

            let toPos = Tools.getToNodePosForNode(popNode, lvItem.node.parent);
            let toScale = popNode.width / lvItem.node.width;
            cc.tween(lvItem.node)
                .to(0.15, { position: cc.v3(toPos), scale: toScale })
                .call(() => {
                    popNode.active = true;
                    popNode.opacity = 255;
                    lvItem.node.active = false;
                }).start();
        }, 0);
    };
    /** 激活一个新道具 */
    hidePopNode(popID: number) {
        let popNode = this.getDownItemForID(popID);
        popNode.active = false;
    };
    /** 显示提示文字 */
    showTipLab(str: string) {
        let tipNode = cc.instantiate(this.tipLabNode);
        tipNode.active = true;
        tipNode.parent = this.tipLabNode.parent;
        tipNode.getChildByName("tipLab").getComponent(cc.Label).string = str;


        this.scheduleOnce(() => {
            tipNode.getChildByName("tipBg").width = tipNode.getChildByName("tipLab").width + 100;
        }, 0);

        cc.tween(tipNode)
            .delay(0.5)
            .by(1, { y: 200 })
            .by(0.5, { y: 100, opacity: -255 })
            .call((target: cc.Node) => {
                target.destroy();
            }).start();
    };

    /** 刷新是否过关 */
    updateWin() {
        if (!this.interJson.winStates || this.interJson.winStates.length != this.finishStateArr.length) { return; }
        for (let i = 0; i < this.finishStateArr.length; i++) {
            if (this.interJson.winStates.indexOf(this.finishStateArr[i]) < 0) {
                return false;
            }
        }
        UIManager.ins.enabledClick(false);

        EventManager.ins.emit(EVENT_NAME_ENUM.STOP_TIME);

        this.scheduleOnce(() => {
            UIManager.ins.enabledClick(false);

            let winInfo = this.getInterTwForName("winGame")
            if (winInfo) {
                this.runNodeTween(this.viewBg, winInfo.interTween);
            } else {
                this.scheduleOnce(() => UIManager.ins.showPop("WinUI", BUNDLE_TYPE_ENUM.GAME), 1);
            }
        }, 0.5);
    };
    updateIsWin() {
        UIManager.ins.enabledClick(false);
        if (this.getIsWin()) {
            this.runNodeTween(this.viewBg, this.getInterTwForName("winGame").interTween);
        } else {
            this.runNodeTween(this.viewBg, this.getInterTwForName("overGame").interTween);
        }
    }

    /** 是否过关 */
    getIsWin() {
        if (this.interJson.winStates.length != this.finishStateArr.length || this.finishStateArr.length <= 0) { return false; }
        for (let i = 0; i < this.finishStateArr.length; i++) {
            if (this.interJson.winStates.indexOf(this.finishStateArr[i]) < 0) {
                return false;
            }
        }
        return true;
    };





    /** 删除已经拥有的状态 */
    removeStates(states: Array<string>) {
        let removeArr = [];
        for (let i = 0; i < states.length; i++) {
            if (this.finishStateArr.indexOf(states[i]) >= 0) {
                Tools.removeArrForValue(this.finishStateArr, states[i]);
                removeArr.push(states[i]);
                i--;
            }
        }
        cc.log("删除状态数组:", this.finishStateArr);
        return removeArr; //返回所有删除成功的状态
    };
    /** 添加已经完成状态 */
    addHaveStates(states: Array<string>) {
        let addArr = [];
        for (let i = 0; i < states.length; i++) {
            if (this.finishStateArr.indexOf(states[i]) < 0) {
                this.finishStateArr.push(states[i]);
                addArr.push(states[i]);
            }
        }
        cc.log("添加状态数组:", this.finishStateArr);
        return addArr;   //返回所有添加成功的状态
    };
    /** 是否已经完成该有的状态 */
    isHaveStates(states: Array<string>) {
        // cc.log(states,this.finishStateArr)
        if (states.length > this.finishStateArr.length) {
            return false;
        }
        for (let i = 0; i < states.length; i++) {
            if (this.finishStateArr.indexOf(states[i]) < 0) {
                return false;
            }
        }
        return true;
    };
    /** 通过ID获取Config */
    getConfigForID(id: number) {
        for (let i = 0; i < this.interJson.downItems.length; i++) {
            const element = this.interJson.downItems[i];
            if (element.id == id) {
                return element;
            }
        }
        return null;
    };
    /** 通过ID 获取Item */
    getDownItemForID(id: number) {
        if (!this.downContent) cc.log("getDownItemForID", this)
        for (let i = 0; i < this.downContent.children.length; i++) {
            let node = this.downContent.children[i];
            if (node.getComponent(LvItem_14).config.id == id) {
                return node;
            }
        }
        return null;
    };
}